<template>
  <div ref="box" class="box">
    <div class="box-left">
      <MenuView :menu-list="sections" @select="menuSelect" :activeMenu="activeMenu"></MenuView>
    </div>
    <div class="box-right">
      <div v-for="(item, index) in sections" ref="anchor" :key="index">
        <h1>{{ item.title }}</h1>
        <component :is="item.componentName" />
      </div>
    </div>
  </div>

</template>

<script>
import MenuView from './components/MenuView.vue';
import InputView from './components/InputView.vue';
import TreeView from './components/TreeView.vue';
import DropView from './components/DropView.vue';
import PreviewView from './components/PreviewView.vue';
import TableView from './components/TableView.vue';
export default {
  name: 'ElementView',
  components: {
    MenuView,
    InputView,
    TreeView,
    DropView,
    PreviewView,
    TableView
  },
  data() {
    return {
      isCollapse: false,
      activeMenu: '0', // 当前激活的锚点索引
      sections: [
        { title: '模糊搜索', componentName: 'InputView' },
        { title: '树结构拖拽', componentName: 'TreeView' },
        { title: 'Drop练习', componentName: 'DropView' },
        { title: '图片预览&下载', componentName: 'PreviewView' },
        { title: 'Table练习', componentName: 'TableView' },
      ]
    }
  },
  mounted() {
    const box = this.$refs.box
    box.addEventListener('scroll', this.updateActiveMenu)
  },
  beforeDestroy() {
    const box = this.$refs.box
    box.removeEventListener('scroll', this.updateActiveMenu)
  },
  methods: {
    menuSelect(index) {
      const anchorElement = this.$refs.anchor[index]
      if (anchorElement) {
        anchorElement.scrollIntoView({ behavior: 'smooth' })
      }
    },
    updateActiveMenu() {
      this.sections.forEach((section, index) => {
        const element = this.$refs.anchor[index]
        const position = element ? element.getBoundingClientRect().top : 0
        if (position <= 0) {
          this.activeMenu = `${index}`
        }
      })
    }
  }

}
</script>


<style lang="scss" scoped>
h1 {
  margin: 0;
}

.box {
  overflow-y: auto;
  height: calc(100vh - 84px);
  padding-left: 10px;

  .box-left {
    position: fixed;

    h2 {
      color: #666;
      font-size: 14px;
      cursor: pointer;
    }

    .active {
      color: var(--primary);
    }
  }

  .box-right {
    padding-left: 210px;
    padding-top: 10px;

  }
}
</style>
